import 'package:flutter/material.dart';
import '../theme/app_theme.dart';


import '../services/app_state_provider.dart';

class CircularProgressPainter extends CustomPainter {
  final double progress;
  final double strokeWidth;
  final Color backgroundColor;
  final Color progressColor;

  const CircularProgressPainter({
    required this.progress,
    required this.strokeWidth,
    required this.backgroundColor,
    required this.progressColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - strokeWidth) / 2;

    
    final backgroundPaint = Paint()
      ..color = backgroundColor
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    canvas.drawCircle(center, radius, backgroundPaint);

    
    final progressPaint = Paint()
      ..color = progressColor
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    
    final sweepAngle = progress * 2 * 3.1415926535;
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -3.1415926535 / 2, 

      sweepAngle,
      false,
      progressPaint,
    );
  }

  @override
  bool shouldRepaint(CircularProgressPainter oldDelegate) {
    return oldDelegate.progress != progress ||
        oldDelegate.strokeWidth != strokeWidth ||
        oldDelegate.backgroundColor != backgroundColor ||
        oldDelegate.progressColor != progressColor;
  }
}

class AnalysisScreen extends StatefulWidget {
  const AnalysisScreen({super.key});

  @override
  State<AnalysisScreen> createState() => AnalysisScreenState();
}

class AnalysisScreenState extends State<AnalysisScreen> {
  
  final bool _isLoading = true;
  
  
  

  String? healthScoreDescription;
  String? changedIndicatorsText;
  String? strongFactorsText;
  String? scoreChangeText;

  @override
  void initState() {
    super.initState();
    _loadHealthAnalysis();
  }
  
  
  Future<void> _loadHealthAnalysis() async {
    try {
      final appState = AppStateProvider.of(context);
      final cycleInfo = appState.currentCycleInfo;
      
      if (cycleInfo != null) {
        
        if (cycleInfo.healthScore >= 80) {
          healthScoreDescription = '良好';
        } else if (cycleInfo.healthScore >= 60) {
          healthScoreDescription = '一般';
        } else {
          healthScoreDescription = '较低';
        }
        
        
        final recordCount = appState.periodRecords.length;
        final changedIndicators = recordCount > 5 ? 1 : 0;
        final strongFactors = recordCount > 10 ? 1 : 0;
        
        
        changedIndicatorsText = '$changedIndicators项指标 ${changedIndicators > 0 ? '明显变化' : '无明显变化'}';
        strongFactorsText = '$strongFactors项影响因素 ${strongFactors > 0 ? '影响强烈' : '影响较弱'}';
        
        
        if (recordCount > 3) {
          scoreChangeText = '+${(recordCount % 5) + 1}分';
        } else {
          scoreChangeText = '0分';
        }
        
        setState(() {});
      }
    } catch (e) {
      debugPrint('加载健康分析数据失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        backgroundColor: AppTheme.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
          color: AppTheme.textPrimary,
        ),
        title: const Text(
          '分析',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimary,
          ),
        ),
      ),
      body: SafeArea(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    
                    Container(
                      margin: const EdgeInsets.all(16),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: AppTheme.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: const [
                          BoxShadow(
                            color: Color(0xFF000000),
                            blurRadius: 10,
                            spreadRadius: 0,
                            offset: Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Icon(Icons.smart_toy_outlined,
                                      size: 16, color: AppTheme.primaryColor),
                                  const SizedBox(width: 6),
                                  const Text('AI 经期健康度',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                        color: AppTheme.textPrimary,
                                      )),
                                ],
                              ),
                              Row(
                                children: [
                                  const Text('综合解读已更新',
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: AppTheme.textSecondary,
                                      )),
                                  const SizedBox(width: 4),
                                  Container(
                                    width: 8,
                                    height: 8,
                                    decoration: const BoxDecoration(
                                      color: Colors.red,
                                      shape: BoxShape.circle,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),

                          const SizedBox(height: 16),

                          
                          Row(
                            children: [
                              
                              Stack(
                                alignment: Alignment.center,
                                children: [
                                  CustomPaint(
                                    size: const Size(120, 120),
                                    painter: const CircularProgressPainter(
                                      progress: 0.69, 

                                      strokeWidth: 20,
                                      backgroundColor: Color(0xFFFEE4E4),
                                      progressColor: Color(0xFFE53935),
                                    ),
                                  ),
                                  Column(
                                    children: [
                                      const Text('69',
                                          style: TextStyle(
                                            fontSize: 32,
                                            fontWeight: FontWeight.bold,
                                            color: Color(0xFFE53935),
                                          )),
                                      const Text('预测得分',
                                          style: TextStyle(
                                            fontSize: 12,
                                            color: AppTheme.textSecondary,
                                          )),
                                    ],
                                  ),
                                ],
                              ),

                              const SizedBox(width: 24),

                              
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(healthScoreDescription ?? '较低',
                                      style: TextStyle(
                                        fontSize: 20,
                                        fontWeight: FontWeight.bold,
                                        color: AppTheme.textPrimary,
                                      )),
                                  const SizedBox(height: 8),
                                  Text(changedIndicatorsText ?? '0项指标 明显变化',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: AppTheme.textSecondary,
                                      )),
                                  const SizedBox(height: 4),
                                  Text(strongFactorsText ?? '0项影响因素 影响强烈',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: AppTheme.textSecondary,
                                      )),
                                  const SizedBox(height: 4),
                                  Row(
                                    children: [
                                      const Text('比上周期',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: AppTheme.textSecondary,
                                          )),
                                      const SizedBox(width: 4),
                                      Text(scoreChangeText ?? '0分',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: scoreChangeText?.contains('+') ?? false ? const Color(0xFF43A047) : const Color(0xFFE53935),
                                          )),
                                    ],
                                  ),
                                  const SizedBox(height: 8),
                                  ElevatedButton(
                                    onPressed: () {},
                                    style: ElevatedButton.styleFrom(
                                      backgroundColor: const Color(0xFFE53935),
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 20, vertical: 8),
                                      shape: RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(20)),
                                    ),
                                    child: const Text(
                                      '立即查看',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: AppTheme.white,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),

                    
                    Container(
                      margin: const EdgeInsets.symmetric(horizontal: 16),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: AppTheme.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: const [
                          BoxShadow(
                            color: Color(0xFF000000),
                            blurRadius: 10,
                            spreadRadius: 0,
                            offset: Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Icon(Icons.calendar_today_outlined,
                                  size: 16, color: AppTheme.primaryColor),
                              const SizedBox(width: 6),
                              const Text('经期预测',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                    color: AppTheme.textPrimary,
                                  )),
                            ],
                          ),

                          const SizedBox(height: 16),

                          
                          const Text(
                            '预测下次经期将于11月12日开始，距离经期开始日还有1天',
                            style: TextStyle(
                              fontSize: 14,
                              color: AppTheme.textSecondary,
                            ),
                          ),

                          const SizedBox(height: 16),

                          
                          Container(
                            padding: const EdgeInsets.symmetric(vertical: 16),
                            decoration: BoxDecoration(
                              color: const Color(0xFFF9F9F9),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Column(
                              children: [
                                const Text('11月',
                                    style: const TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                      color: AppTheme.textPrimary,
                                    )),
                                const SizedBox(height: 8),
                                
                                GridView.builder(
                                  shrinkWrap: true,
                                  physics: const NeverScrollableScrollPhysics(),
                                  gridDelegate:
                                      const SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 7,
                                    crossAxisSpacing: 8,
                                    mainAxisSpacing: 8,
                                  ),
                                  itemCount: 30,
                                  itemBuilder: (context, index) {
                                    return Container(
                                      width: 40,
                                      height: 40,
                                      decoration: BoxDecoration(
                                        color: index == 11
                                            ? const Color(0xFFE53935)
                                            : const Color(0x00000000),
                                        borderRadius: BorderRadius.circular(20),
                                      ),
                                      child: Center(
                                        child: Text(
                                          '${index + 1}',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: index == 11
                                                ? AppTheme.white
                                                : AppTheme.textSecondary,
                                            fontWeight: index == 11
                                                ? FontWeight.bold
                                                : FontWeight.normal,
                                          ),
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),

                    
                    Container(
                      margin:
                          const EdgeInsets.only(top: 16, left: 16, right: 16),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: AppTheme.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: const [
                          BoxShadow(
                            color: Color(0xFF000000),
                            blurRadius: 10,
                            spreadRadius: 0,
                            offset: Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Icon(Icons.show_chart_outlined,
                                      size: 16, color: AppTheme.primaryColor),
                                  const SizedBox(width: 6),
                                  const Text('周期变化',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                        color: AppTheme.textPrimary,
                                      )),
                                ],
                              ),
                              Icon(Icons.chevron_right,
                                  size: 20, color: AppTheme.textLight),
                            ],
                          ),

                          const SizedBox(height: 16),

                          
                          const Text('最近1个周期（9月18日-10月14日）',
                              style: TextStyle(
                                fontSize: 14,
                                color: AppTheme.textSecondary,
                              )),

                          const SizedBox(height: 16),

                          
                          Container(
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: const Color(0xFFF9F9F9),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Text('周期天数',
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: AppTheme.textSecondary,
                                        )),
                                    const SizedBox(height: 8),
                                    Row(
                                      children: [
                                        const Text('27',
                                            style: TextStyle(
                                              fontSize: 28,
                                              fontWeight: FontWeight.bold,
                                              color: AppTheme.textPrimary,
                                            )),
                                        const SizedBox(width: 8),
                                        Container(
                                          padding: const EdgeInsets.symmetric(
                                              horizontal: 8, vertical: 2),
                                          decoration: BoxDecoration(
                                            color: const Color(0xFFE8F5E9),
                                            borderRadius:
                                                BorderRadius.circular(4),
                                          ),
                                          child: const Text('正常',
                                              style: TextStyle(
                                                fontSize: 12,
                                                color: Color(0xFF43A047),
                                              )),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Text('和前1个周期',
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: AppTheme.textSecondary,
                                        )),
                                    const SizedBox(height: 8),
                                    const Text('相同',
                                        style: TextStyle(
                                          fontSize: 28,
                                          fontWeight: FontWeight.bold,
                                          color: AppTheme.textPrimary,
                                        )),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),

                    
                    Container(
                      margin:
                          const EdgeInsets.only(top: 16, left: 16, right: 16),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: AppTheme.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: const [
                          BoxShadow(
                            color: Colors.black,
                            blurRadius: 10,
                            spreadRadius: 0,
                            offset: Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Icon(Icons.bar_chart_outlined,
                                      size: 16, color: AppTheme.primaryColor),
                                  const SizedBox(width: 6),
                                  const Text('近期周期天数',
                                      style: TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                        color: AppTheme.textPrimary,
                                      )),
                                ],
                              ),
                              Icon(Icons.chevron_right,
                                  size: 20, color: AppTheme.textLight),
                            ],
                          ),

                          const SizedBox(height: 16),

                          
                          Column(
                            children: [
                              
                              Container(
                                margin: const EdgeInsets.only(bottom: 16),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Container(
                                      width: 80,
                                      child: const Text('10月15日',
                                          style: TextStyle(
                                            fontSize: 12,
                                            color: AppTheme.textSecondary,
                                          )),
                                    ),
                                    const Text('提前1天',
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: AppTheme.textSecondary,
                                        )),
                                    Expanded(
                                      child: Container(
                                        margin: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        height: 28,
                                        decoration: BoxDecoration(
                                          color: const Color(0xFFFEE4E4),
                                          borderRadius:
                                              BorderRadius.circular(4),
                                        ),
                                        child: Align(
                                          alignment: Alignment.centerRight,
                                          child: const Padding(
                                            padding: EdgeInsets.only(right: 8),
                                            child: Text(
                                              '当前周期28天',
                                              style: TextStyle(
                                                fontSize: 12,
                                                color: Color(0xFFE53935),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),

                              
                              Container(
                                margin: const EdgeInsets.only(bottom: 16),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Container(
                                      width: 80,
                                      child: const Text('9月18日',
                                          style: TextStyle(
                                            fontSize: 12,
                                            color: AppTheme.textSecondary,
                                          )),
                                    ),
                                    const Text('提前1天',
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: AppTheme.textSecondary,
                                        )),
                                    Expanded(
                                      child: Container(
                                        margin: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        height: 28,
                                        decoration: BoxDecoration(
                                          color: const Color(0xFFFEE4E4),
                                          borderRadius:
                                              BorderRadius.circular(4),
                                        ),
                                        child: const Align(
                                          alignment: Alignment.centerRight,
                                          child: Padding(
                                            padding: EdgeInsets.only(right: 8),
                                            child: Text('27天',
                                                style: TextStyle(
                                                  fontSize: 12,
                                                  color:
                                                      const Color(0xFFE53935),
                                                )),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),

                              
                              Container(
                                margin: const EdgeInsets.only(bottom: 8),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Container(
                                      width: 80,
                                      child: const Text('8月22日',
                                          style: TextStyle(
                                            fontSize: 12,
                                            color: AppTheme.textSecondary,
                                          )),
                                    ),
                                    const Text('准时',
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: AppTheme.textSecondary,
                                        )),
                                    Expanded(
                                      child: Container(
                                        margin: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        height: 28,
                                        decoration: BoxDecoration(
                                          color: const Color(0xFFFEE4E4),
                                          borderRadius:
                                              BorderRadius.circular(4),
                                        ),
                                        child: const Align(
                                          alignment: Alignment.centerRight,
                                          child: Padding(
                                            padding: EdgeInsets.only(right: 8),
                                            child: Text('27天',
                                                style: TextStyle(
                                                  fontSize: 12,
                                                  color:
                                                      const Color(0xFFE53935),
                                                )),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),

                    
                    const SizedBox(height: 8),
                  ],
                ),
              ),
      ),
    );
  }
}
